<?php

class dao extends main{
	protected static $PDO;
	protected static $nb_queries;

	public static function init(){
		self::$nb_queries = 0;
		if(in_array(parent::getConfig("db_type"), PDO::getAvailableDrivers())){
			try{
				$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
				self::$PDO = new PDO(parent::getConfig("db_type").":host=". parent::getConfig("db_host") .";dbname=". parent::getConfig("db_name"), parent::getConfig("db_user"), parent::getConfig("db_passwd"), $pdo_options);
			}catch(PDOException $e){
				die(error::show("bdd".$e->getCode() ,__FILE__,(__LINE__-2),$requete. "\nmessage : ".$e->getMessage()));
			}
			
			try{
				self::$PDO->query("SET NAMES 'utf8'");
			}catch(PDOException $e){
				die(error::show("bdd".$e->getCode() ,__FILE__,(__LINE__-2),$requete. "\nmessage : ".$e->getMessage()));
			}
		}else{
			die(error::show("bdddriver" ,__FILE__,(__LINE__-11)));
		}
	}

	public static function exec_request($requete)
	{
		try{
			$result = self::$PDO->query($requete);
		}catch(PDOException $e){
			$trace=debug_backtrace(false);
			
			$file = explode('/',$trace[1]['file']);
			$file = $file[count($file)-1];
			$line = $trace[1]['line'];
			
			die(error::show("bdd".$e->getCode() ,$file,$line,$requete. "\nmessage : ".$e->getMessage()));
		}
		
		self::$nb_queries ++;
		if($result == true && preg_match('#^INSERT INTO#',$requete)){
			$lastId = self::lastInsertId();
			if($lastId != false)
				return $lastId;
			else
				return true;
		}else
			return $result;
	}

	public static function request_array($requete)
	{
		try{
			$result = self::$PDO->query($requete);
		}catch(PDOException $e){
			$trace=debug_backtrace(false);
			
			$file = explode('/',$trace[1]['file']);
			$file = $file[count($file)-1];
			$line = $trace[1]['line'];
			
			die(error::show("bdd".$e->getCode() ,$file,$line,$requete. "\nmessage : ".$e->getMessage()));
		}
		
		if($result->columnCount() > 0){
			$data = array();
			$result->setFetchMode(PDO::FETCH_NUM);
			$data = $result->fetchAll($result);
		}else
			$data = false;
		self::$nb_queries ++;
		return $data;
	}

	public static function request_assoc($requete)
	{
		try{
			$result = self::$PDO->query($requete);
		}catch(PDOException $e){
			$trace=debug_backtrace(false);
			
			$file = explode('/',$trace[1]['file']);
			$file = $file[count($file)-1];
			$line = $trace[1]['line'];
			
			die(error::show("bdd".$e->getCode() ,$file,$line,$requete. "\nmessage : ".$e->getMessage()));
		}
		
		if($result->columnCount() > 0){
			$data = array();
			$result->setFetchMode(PDO::FETCH_ASSOC);
			$data = $result->fetchAll();
		}else
			$data = false;
		self::$nb_queries ++;
		return $data;
	}
	
	public static function lastInsertId(){
		return self::$PDO->lastInsertId();
	}
	
	public static function getNbQueries(){
		return self::$nb_queries;
	}

	public function __destruct()
	{
		//PDO ne necessite pas de method close, il le fait automatiquement a la destruction de l'objet PDO
		return true;
	}
};
?>